import Vue from 'vue';
import axios from 'axios';
import { message } from 'ant-design-vue';
import store from '@/store';
import router from '@/router';

let messageDelay = false;

const noAuthWhiteListRoute = ['/health/auth/captcha']; // 请求时不需要带上token的路由列表
const ifRouteExist = (arry, path) => arry.some((route) => path.indexOf(route) > -1);

axios.defaults.timeout = 30000;
// axios.defaults.withCredentials = true;
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';

axios.interceptors.request.use((config) => {
  store.commit('setRequesting', true);
  if (store.state.token !== '' && !ifRouteExist(noAuthWhiteListRoute, config.url)) {
    // eslint-disable-next-line no-param-reassign
    // // console.log('请求时', store.state.token);
    config.headers['X-Auth-Token'] = store.state.token;
  }
  return config;
}, (error) => Promise.reject(error));

// http响应拦截器
axios.interceptors.response.use((res) => {
  const { data } = res;
  if (res.headers['x-auth-token']) {
    // // console.log('登录前', store.state.token);
    store.commit('setToken', res.headers['x-auth-token']);
    // // console.log('登录后', store.state.token);
  }
  store.commit('setRequesting', false);
  return data;
}, (error) => {
  setTimeout(() => { store.commit('setRequesting', false); }, 300);
  if (!messageDelay) {
    messageDelay = true;
    if (error.message.includes('timeout')) {
      message.error('请求超时，稍后请重试');
    } else if (error.message.includes('Network Error')) {
      message.error('网络错误，请检查网络');
    } else {
      console.log(error);
      switch (error.response.status) {
        case 401:
          if (error.response.data.code === 'S.001.AUTH.CREDENTIALS_EXPIRED' || error.response.data.data.say) {
            message.error('登录过期');
            store.commit('setToken', ''); // 清除token
            router.push('/login');
          } else {
            message.error(error.response.data.tip);
          }
          break;
        default:
          message.error(error.response.data.tip || error.message);
          break;
      }
    }
    setTimeout(() => { messageDelay = false; }, 1000);
  }
  return Promise.reject(error);
});

Vue.prototype.$axios = axios;
